<script lang="ts">
    import { Popover } from "../Popover";
    import { useClassList } from "../utils/useClassList";
    import type { MenuContextData, MenuItemProps } from "./Menu";
    import { useMenuContext } from "./Menu.svelte";
    import Icon from "../Common/Icons/Icon.svelte";
    import { fade, slide } from "svelte/transition";

    const props: MenuItemProps = $props();

    if (!props.isSubmenuTitle && !props.name) {
        console.warn("MenuItem need name prop");
    }

    let min = $state(false);
    const ctx: MenuContextData = useMenuContext();
    const store = ctx.getStore();
    const level = ctx.level;
    const parentName = props.isSubmenuTitle ? props.parentName! : ctx.parentName;
    // 获取上级的padding
    const parentPadding = level * 16;
    // 子菜单增加padding
    const padding = props.isSubmenuTitle ? parentPadding : parentPadding + 16;

    const classList = $derived(
        useClassList(props, "cm-menu-item", {
            "cm-menu-item-disabled": props.disabled,
            "cm-menu-item-active": !props.isSubmenuTitle && props.name && store.activeName === props.name,
        })
    );

    // 展开的副作用，更新菜单项的padding
    $effect(() => {
        let flag = false;
        flag = store.min && parentName === "__root";
        min = flag;
    });

    if (!props.isSubmenuTitle) {
        const item = {
            name: props.name,
            parent: null,
            children: [],
        };
        if (ctx && props.name) {
            ctx.treeMap[props.name] = item;
            if (parentName === "__root") {
                ctx?.tree.push(item);
            } else {
                const parent = ctx.treeMap[parentName];
                item.parent = parent;
                parent.children.push(item);
            }
        }
    }

    const onSelect = () => {
        if (props.isSubmenuTitle && !store.min) {
            props.onselect?.();
        } else {
            ctx?.onSelect(props.name!, props.data);
        }
    };
</script>

<Popover disabled={!min || props.isSubmenuTitle} align="right" arrow theme={ctx.getTheme()}>
    {#snippet content()}
        {#if min}
            <div class="cm-menu-item-text">
                {@render props.children?.()}
            </div>
        {/if}
    {/snippet}
    <!-- svelte-ignore a11y_click_events_have_key_events -->
    <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
    <li class={classList} style={`padding-left: ${ctx?.dir() === "h" || store.min ? "16px" : padding + "px"}`} onclick={onSelect}>
        <div class="cm-menu-item-icon">{@render props.icon?.()}</div>
        {#if !min}
            <div class="cm-menu-item-text" in:slide={{ duration: 250, axis: "x" }} out:slide={{ duration: 250, axis: "x" }}>{@render props.children?.()}</div>
        {/if}
        {#if !min && props.cert}
            <div class="cm-menu-item-cert">
                <Icon icon="chevronDown" size={14} />
            </div>
        {/if}
    </li>
</Popover>
